package com.mall.common.dao.impl;

import static com.mall.common.Constants.OPERATE_TYPE_NORMAL;

import java.util.List;
import java.util.Set;

import org.springframework.stereotype.Repository;

import com.mall.common.dao.OperateDao;
import com.mall.common.domain.manage.Operate;
import com.mall.common.domain.manage.Role;

/**
 * Dao实现类 - 资源
 */

@Repository
public class OperateDaoImpl extends BaseDaoImpl<Operate, Long> implements OperateDao {
	
	// 处理关联
	@Override
	public void remove(Operate operate) {
		if (operate.getType() == OPERATE_TYPE_NORMAL) {
			super.remove(operate);
			return;
		}
		Set<Role> roleSet = operate.getRoleSet();
		if (roleSet != null) {
			for (Role role : roleSet) {
				role.getOperateSet().remove(operate);
			}
		}
		super.remove(operate);
	}

	// 忽略isSystem=true的对象。
	@Override
	public void update(Operate operate) {
		super.update(operate);
	}
	
	// 根据priority排序
	@SuppressWarnings("unchecked")
	@Override
	public List<Operate> getAll() {
		String hql = "from Operate operate order by operate.priority asc operate.createDate desc";
		return entityManager.createQuery(hql).getResultList();
	}

	// 根据operate的priority升序、operate的创建时间降序排序
	@Override
	@SuppressWarnings("unchecked")
	public List<Operate> getList(String propertyName, Object value) {
		String hql = "from Operate operate where operate." + propertyName + "=? order by operate.priority asc operate.createDate desc";
		return entityManager.createQuery(hql).setParameter(0, value).getResultList();
	}
}